package com.iflytek.aidemo.teacher;

import android.app.DatePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AlertDialog;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.components.MarkerView;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.highlight.Highlight;

import com.iflytek.aidemo.R;
import com.iflytek.aidemo.api.ApiService;
import com.iflytek.aidemo.api.ApiServiceImpl;
import com.iflytek.aidemo.model.ApiResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class ClassScoreTrendActivity extends AppCompatActivity {

    private static final DateTimeFormatter DF = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    private LineChart lineChart;
    private EditText etStart, etEnd;
    private Button btnApply;
    private TextView tvTitle;

    private int classId;
    private String className;

    private final ApiService api = new ApiServiceImpl();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_class_score_trend);

        //获取数据
        classId = getIntent().getIntExtra("class_id", -1);
        className = getIntent().getStringExtra("class_name");
        if (className == null) className = "班级";

        ImageButton back = findViewById(R.id.btn_back);
        tvTitle = findViewById(R.id.tv_title);
        lineChart = findViewById(R.id.line_chart);
        etStart = findViewById(R.id.et_start_date);
        etEnd = findViewById(R.id.et_end_date);
        btnApply = findViewById(R.id.btn_apply);

        if (back != null) back.setOnClickListener(v -> finish());
        if (tvTitle != null) tvTitle.setText(className + " 成绩统计");

        setupChart();
        setupDatePickers();

        //默认当前周
        LocalDate end = LocalDate.now();
        LocalDate start = end.minusDays(6);
        etStart.setText(start.format(DF));
        etEnd.setText(end.format(DF));

        btnApply.setOnClickListener(v -> loadAndRender());

        //加载数据
        loadAndRender();
    }

    private void setupChart() {
        lineChart.getDescription().setEnabled(false);
        lineChart.setNoDataText("暂无数据");

        XAxis xAxis = lineChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setGranularity(1f);
        xAxis.setDrawGridLines(false);

        YAxis left = lineChart.getAxisLeft();
        left.setAxisMinimum(0f);
        left.setAxisMaximum(100f);
        left.setGranularity(10f);
        left.setDrawAxisLine(true);
        left.setDrawGridLines(true);
        left.setDrawLabels(true);
        lineChart.getAxisRight().setEnabled(false);
    }

    private void setupDatePickers() {
        etStart.setOnClickListener(v -> showDatePicker(etStart));
        etEnd.setOnClickListener(v -> showDatePicker(etEnd));
    }

    private void showDatePicker(EditText target) {
        Calendar cal = Calendar.getInstance();
        int y = cal.get(Calendar.YEAR);
        int m = cal.get(Calendar.MONTH);
        int d = cal.get(Calendar.DAY_OF_MONTH);
        DatePickerDialog dlg = new DatePickerDialog(this, (view, yy, mm, dd) -> {
            String date = String.format("%04d-%02d-%02d", yy, mm + 1, dd);
            target.setText(date);
        }, y, m, d);
        dlg.show();
    }

    private void loadAndRender() {
        if (classId <= 0) {
            Toast.makeText(this, "班级信息缺失", Toast.LENGTH_SHORT).show();
            return;
        }
        String startStr = etStart.getText().toString().trim();
        String endStr = etEnd.getText().toString().trim();
        if (startStr.isEmpty() || endStr.isEmpty()) {
            Toast.makeText(this, "请选择时间范围", Toast.LENGTH_SHORT).show();
            return;
        }
        LocalDate start;
        LocalDate end;
        try {
            start = LocalDate.parse(startStr, DF);
            end = LocalDate.parse(endStr, DF);
        } catch (Exception e) {
            Toast.makeText(this, "日期格式错误", Toast.LENGTH_SHORT).show();
            return;
        }
        if (end.isBefore(start)) {
            Toast.makeText(this, "结束日期不能早于开始日期", Toast.LENGTH_SHORT).show();
            return;
        }

        //从后端获取所选时间段的数据
        new Thread(() -> {
            List<Entry> entries = new ArrayList<>();
            List<String> labels = new ArrayList<>();

            LocalDate cur = start;
            int xIndex = 0;
            while (!cur.isAfter(end)) {
                String day = cur.format(DF);
                try {
                    ApiResponse<JSONObject> resp = api.getClassOverviewWithStudents(classId, day);
                    if (resp != null && resp.getCode() == 200 && resp.getData() != null) {
                        JSONObject data = resp.getData();
                        int totalCount = data.optInt("totalCount", 0);
                        JSONArray records = data.optJSONArray("records");
                        double averageRate = data.optDouble("averageRate", 0.0);
                        boolean hasData = totalCount > 0 && records != null && records.length() > 0;
                        if (hasData) {
                            float percent = (float) (averageRate * 100.0);
                            entries.add(new Entry(xIndex, percent));
                            labels.add(day);
                            xIndex++;
                        }
                    }
                } catch (Exception ignore) {}
                cur = cur.plusDays(1);
            }

            runOnUiThread(() -> render(entries, labels));
        }).start();
    }

    private void render(List<Entry> entries, List<String> labels) {
        if (entries.isEmpty()) {
            lineChart.clear();
            lineChart.invalidate();
            Toast.makeText(this, "所选时间段暂无数据", Toast.LENGTH_SHORT).show();
            return;
        }

        LineDataSet dataSet = new LineDataSet(entries, "班级平均分");
        dataSet.setColor(0xFF3F51B5);
        dataSet.setCircleColor(0xFF3F51B5);
        dataSet.setLineWidth(2f);
        dataSet.setCircleRadius(3f);
        dataSet.setDrawValues(false);
        dataSet.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER);

        LineData lineData = new LineData(dataSet);
        lineChart.setData(lineData);

        XAxis xAxis = lineChart.getXAxis();
        xAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                int i = (int) value;
                if (i >= 0 && i < labels.size()) return labels.get(i).substring(5); // show MM-DD
                return "";
            }
        });

        // 绑定点选事件，使用与X轴一致的labels
        attachTapHandler(labels);
        lineChart.invalidate();
    }

    private void attachTapHandler(List<String> labels) {
        lineChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            @Override
            public void onValueSelected(Entry e, Highlight h) {
                int index = (int) e.getX();
                if (index < 0 || index >= labels.size()) return;
                String date = labels.get(index);
                new AlertDialog.Builder(ClassScoreTrendActivity.this)
                        .setTitle("查看当天成绩")
                        .setMessage("是否查看 " + date + " 的成绩预览？")
                        .setPositiveButton("确定", (dialog, which) -> {
                            android.content.Intent intent = new android.content.Intent(ClassScoreTrendActivity.this, TeacherScoreOverviewActivity.class);
                            intent.putExtra("jump_date", date);
                            intent.putExtra("jump_class_id", classId);
                            intent.addFlags(android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP | android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP);
                            startActivity(intent);
                            finish();
                        })
                        .setNegativeButton("取消", null)
                        .show();
            }

            @Override
            public void onNothingSelected() { }
        });
    }
}
